#include "contactsdialog.h"
#include "ui_contactsdialog.h"
#include"../widget/chatuserwid.h"
#include"../widget/applicatwid.h"
#include"globalsignal.h"
#include <tcpmgr.h>

ContactsDialog::ContactsDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ContactsDialog)
    ,_newFriend(new ChatUserWid("新的朋友"))
{
    ui->setupUi(this);
    ui->stackedWidget->setCurrentIndex(1);

    _newFriend->setContactsStyle();
    _newFriend->setHeadPortrait(QPixmap(":/img/qrc/img/newFiredn.png"));
    connect(_newFriend, &ChatUserWid::sig_switch_user, this, [this]{
        ui->stackedWidget->setCurrentIndex(0);
    });
    QListWidgetItem *item{new QListWidgetItem(ui->listWidget)};
    ui->listWidget->setItemWidget(item, _newFriend);
    item->setSizeHint(_newFriend->sizeHint());
    ui->listWidget->insertItem(_userNum++, item);

    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_add_friend_req, this, &ContactsDialog::slot_add_friend_req);
    connect(GlobalSignal::GetInstance().get(), &GlobalSignal::sig_add_friend_req, this, &ContactsDialog::slot_add_friend_req);
    connect(GlobalSignal::GetInstance().get(), &GlobalSignal::sig_add_friend, this, &ContactsDialog::slot_add_friend);
}

ContactsDialog::~ContactsDialog()
{
    delete ui;
}

void ContactsDialog::slot_switch_user(const QString &name)
{
    qDebug() << name;
    ui->stackedWidget->setCurrentIndex(1);
    ui->label_2->setText(name);
    ui->label->setPixmap(QPixmap(AvatarPath.arg(name)));
}

void ContactsDialog::slot_add_friend_req(const QString &name, const QString &message)
{
    _newFriend->addOne();
    ApplicatWid *applicatWid{new ApplicatWid};
    applicatWid->setUser(name, message);
    QListWidgetItem *aitem{new QListWidgetItem(ui->listWidget_2)};
    ui->listWidget_2->setItemWidget(aitem, applicatWid);
    aitem->setSizeHint(applicatWid->sizeHint());
    ui->listWidget_2->insertItem(_userNum++, aitem);
}

void ContactsDialog::slot_add_friend(const QString &name)
{
    ChatUserWid *customWidget{new ChatUserWid(name)};
    connect(customWidget, &ChatUserWid::sig_switch_user, this, &ContactsDialog::slot_switch_user);
    customWidget->closeRedDot();
    customWidget->setContactsStyle();
    QListWidgetItem *item{new QListWidgetItem(ui->listWidget)};
    ui->listWidget->setItemWidget(item, customWidget);
    item->setSizeHint(customWidget->sizeHint());
    ui->listWidget->insertItem(_userNum++, item);
}

void ContactsDialog::on_pushButton_clicked()
{
    emit sig_switch_user(ui->label_2->text());
}

